package virtualinit;

import virtualinit.util.CommonUtil;
import virtualinit.util.JdbcUtil;
import virtualinit.util.Log;
import virtualinit.util.TimeUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class O2oInit extends AbstractInit {
    static Log log = Log.instance;

    public void doStart() throws Exception {
        init();
        task.init(this);
        o2oInit();
    }

    @Override
    public String getTaskName() {
        return "o2o同步任务";
    }

    /**
     * o2o 店仓id 一致
     * <p>
     * depot_store_id(ds_id) b2c为仓库id o2o为门店id',
     */
    private void o2oInit() throws Exception {
        Map<String, SqlHolder> sqlCache = new HashMap<>(10000);
        log.info("\n\n----------------------------------");
        long start = System.currentTimeMillis();
        log.info("O2o 同步开始...");
        String now = TimeUtil.now();
        // 把所有的l1 l2 l3 都查出来
        List<Map<String, Object>> allL1l2l3 = JdbcUtil.executeToMap(scheduleConn, l1l2l3AllSql.replace("?", JdbcUtil.quoteIdentifier(scheduleDbName)));
        log.info("缓存所有l1 l2 l3 大小:{} {}", allL1l2l3.size(), TimeUtil.countTimeCn(start));
        Map<String, List<Map<String, Object>>> ds_id_toL1l1l2 = allL1l2l3.stream().collect(Collectors.groupingBy(e -> e.get("ds_id").toString()));

        int i = 2;
        try {
            for (i = 2; i < 50; i++) {
                long sourceBefore = totalSourceSize;
                String sql = CommonUtil.format("select store_id,sku_id from ?.st_stock_" + i + " where is_deleted=0",
                        JdbcUtil.quoteIdentifier(storageDbName)) + config.initVirtualStockConfig.getLimit();
                log.info("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 加载数据源表：st_stock_{}", i);
                JdbcUtil.exeCursorMap(storageConn, sql, row -> {
                    totalSourceSize++;
                    String depot_store_id = row.get("store_id").toString();
                    Object sku_id = row.get("sku_id");
                    List<Map<String, Object>> mapList = ds_id_toL1l1l2.get(depot_store_id);
                    if (mapList != null) {
                        for (Map<String, Object> d : mapList) {
                            Object virtual_depot_id = d.get("id");
                            String channelId = (String) d.get("cs_id");
                            String storeId = (String) d.get("ds_id");
                            Object is_share = d.get("is_share");

                            SqlHolder sqlHolder = super.getSqlHolder(sqlCache, channelId, storeId);
                            if (sqlHolder == null)
                                continue;

                            totalTarget++;
                            sqlHolder.addValue(1, 1, now, now,
                                    virtual_depot_id, channelId, storeId, sku_id, 1, is_share);
                            if (sqlHolder.count % config.batchSize == 0) {
                                super.addSql(sqlHolder);
                                sqlHolder.reset();
                            }
                        }
                    }
                });
                log.info("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 数据源表：st_stock_{} size:{}", i, totalSourceSize - sourceBefore);
                sourceBefore = totalSourceSize;
            }
        } catch (Exception e) {
            String msg = e.getMessage();
            if (msg != null && msg.contains("Table") && msg.contains("doesn't exist")) {
                log.info("数据源全部查询完毕, 共{}张表", i - 1);
                finished = true;
            } else {
                throw new RuntimeException(e);
            }
        }

        sqlCache.values().forEach(super::addSql);
        task.handleCompleted();
        log.info("o2o 同步结束 total:{}  数据源条数：{} 插入条数：{} 渠道统计：{}",
                totalTarget, totalSourceSize, task.getWatch().totalCount.get(), tbCounts);
        log.info("----------------------------------\n\n");
    }

    static String l1l2l3AllSql = "SELECT svd.id,if(svd.is_top=2,0,svd.is_share) as is_share,svdc.cs_id,svdd.ds_id \n" +
            "FROM\n" +
            "\t?.sc_virtual_depot AS svd\n" +
            "\tINNER JOIN ?.sc_virtual_depot_cs svdc ON svd.id = svdc.virtual_depot_id\n" +
            "\tINNER JOIN ?.sc_virtual_depot_ds svdd ON svd.id = svdd.virtual_depot_id \n" +
            "WHERE\n" +
            "\tsvd.mode_type = 2 AND svd.LEVEL = 1 AND svd.is_deleted=0\n" +
            "UNION ALL\n" +
            "\n" +
            "SELECT svd.id,if(svd.is_top=2,0,svd.is_share) as is_share,svsg.cs_id,svdd.ds_id \n" +
            "FROM\n" +
            "\t?.sc_virtual_depot AS svd\n" +
            "\tINNER JOIN ?.sc_virtual_shared_group svsg ON svd.id = svsg.virtual_depot_id\n" +
            "\tINNER JOIN ?.sc_virtual_depot_ds svdd ON svd.id = svdd.virtual_depot_id \n" +
            "WHERE\n" +
            "\tsvd.mode_type = 2 AND svd.LEVEL = 1 AND svd.is_deleted=0\n" +
            "UNION ALL\n" +
            "\n" +
            "SELECT svd.id,if(svd.is_top=2,0,svd.is_share) as is_share,svdc.cs_id,svdd.ds_id \n" +
            "FROM\n" +
            "\t?.sc_virtual_depot AS svd\n" +
            "\tINNER JOIN ?.sc_virtual_depot_cs svdc ON svd.id = svdc.virtual_depot_id\n" +
            "\tINNER JOIN ?.sc_virtual_depot_ds svdd ON svd.id = svdd.virtual_depot_id \n" +
            "WHERE\n" +
            "\tsvd.mode_type = 2 AND svd.LEVEL = 2 AND svd.is_deleted=0";

}
